$(function ()
{
    //代码
   loadTeacherList();

});

function loadTeacherList() {

    $.ajax({
        url:"/api/teacher/list"
    }).done(function (date) {
        // console.log(date)
        let html ="";
        date.forEach((element,index) => {
            html += "<tr>"

            html += "<td>" + element.id + "</td>"
            html += "<td>" + element.name + "</td>"
            html += "<td>" + element.sex + "</td>"
            html += "<td>" + element.age + "</td>"
            html += "<td>" + element.tno + "</td>"
            html += "<td>" + element.password + "</td>"
            html += "<td>  <a href='#' onClick='showTeacherDlg("+element.id+")'> 编辑</a></td>"
            html += "</tr>"

        })

        $("#teacherTb").html(html)

    });

}


let layerIndex;



/**
 * 弹出老师信息对话框
 */
function showTeacherDlg(id) {
    let title = "新增老师";
    $("#formId").css("display","block");

    //新增表单
    if (id) {
        // 是编辑
        title = "编辑老师";
        // 读取老师信息并赋值
        $.ajax({
            url: "/api/teacher/" + id,
            method: "GET"
        }).done(function(result) {
            console.log(result);
            $.each(result, function(key, value) {
                // 修改选择器，确保选择的是 #teacherForm 内的字段
                var field = $('#teacherForm').find('[name="' + key + '"]');

                if (field.is('input:radio')) {
                    field.filter('[value="' + value + '"]').prop('checked', true); // 选中对应的单选按钮
                } else if (field.is('input:checkbox')) {
                    field.prop('checked', value === "yes"); // 选中复选框
                } else {
                    field.val(value); // 填充文本框或其他字段
                }
            });
        });
    }else {
        $("#teacherForm")[0].reset();
        $("#formId").css("display","none");
    }

    // 打开弹窗的代码应该在 if-else 结构之外
    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ['520px', 'auto'],
        content: $('#teacherForm')
    });
}


//阻止全部刷新
layui.use(function () {

    //验证表单是否合法
    layui.form.on('submit(teacher-dlg)',function (data) {
    event.preventDefault();//组织表单默认提交

        commitTeacherDlg();

    })


})


function commitTeacherDlg() {
    let id = $("#id").val()
    let formData = $("#teacherForm").serialize();
    if(id != null && id!=""){
        //是更新
        $.ajax({
            url: "/api/teacher/update",
            method: "PUT",
            data: formData
        }).done(function(result) {
            console.log(result);
            if (result.id) {
                // 刷新老师列表
                loadTeacherList();
                console.log("add success");
                if (layerIndex) {
                    layer.close(layerIndex); // 关闭弹出层
                }
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.error("Request failed: " + textStatus + "-" + errorThrown);
            alert("An error occurred. Please try again.");
        });

    }else{
        //把表单数据提交，更新

        $.ajax({
            url: "/api/teacher/add",
            method: "POST",
            data: formData
        }).done(function(result) {
            console.log(result);
            if (result.id) {
                // 刷新老师列表
                loadTeacherList();
                console.log("add success");
                if (layerIndex) {
                    layer.close(layerIndex); // 关闭弹出层
                }
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.error("Request failed: " + textStatus + "-" + errorThrown);
            alert("An error occurred. Please try again.");
        });


    }



        $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled"); // 重新启用按钮
}